<?php
// +----------------------------------------------------------------------
// | 众联TK架构 [ ZoomTk ]
// +----------------------------------------------------------------------
// | 版权所有 2017~2037 成都众联思索科技有限公司 [ http://www.zoomtk.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://www.sopvip.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\member\model;
use think\helper\Hash;
use think\Model;
use think\Db;

/**
 * 会员用户模型
 * @package app\admin\model
 */
class User extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = '__MEMBER_USER__';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 对密码进行加密
    public function setPasswordAttr($value)
    {
        return Hash::make((string)$value);
    }

    // 获取注册ip
    public function setSignupIpAttr()
    {
        return get_client_ip(1);
    }

    /**
     * 用户登录
     * @param string $username 用户名
     * @param string $password 密码
     * @param bool $rememberme 记住登录
     * @author Sunday <153788231@qq.com>
     * @return bool|mixed
     */
    public function login($username = '', $password = '', $rememberme = false)
    {
        $username = trim($username);
        $password = trim($password);
        // 匹配登录方式
        if (preg_match("/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/", $username)) {
            // 邮箱登录
            $map['member_email'] = $username;
        } elseif (preg_match("/^1\d{10}$/", $username)) {
            // 手机号登录
            $map['member_mobile'] = $username;
        } else {
            // 用户名登录
            $map['member_name'] = $username;
        }
        $map['status'] = 1;
        // 查找用户
        $user = $this::get($map);
        if (!$user) {
            $this->error = '用户不存在或被禁用！';
        } else {
            if (md5($password)!=$user->member_passwd) {
                $this->error = '密码错误！';
            } else {
                $uid = $user->member_id;
                // 更新登录信息
                $user->member_login_time = request()->time();
                $user->member_login_ip   = get_client_ip(1);
                if ($user->save()) {
                    // 自动登录
                    $this->autoLogin($this::get($uid), $rememberme);
                };
                return $uid;
            }
        }
        return false;
    }
    /**
     * 自动登录
     * @param $user 用户对象
     * @param bool $rememberme 是否记住登录，默认7天
     * @author Sunday <153788231@qq.com>
     */
    public function autoLogin($user, $rememberme = false)
    {
        // 记录登录SESSION和COOKIES
        $auth = array(
            'uid'             => $user->member_id,
            'avatar'          => $user->member_avatar,
            'username'        => $user->member_name,
            'nickname'        => $user->nickname,
            'member_login_time' => $user->member_login_time,
            'member_login_ip'   => get_client_ip(1),
            'oauth_token_secret' =>encrypt(serialize(array('member_name'=>$user->member_name,'member_passwd'=>$user->member_passwd))),
        );
        $stoer_info=Db::name('seller')->where('member_id',$user->member_id)->find();
        if($stoer_info['store_id']){
            session('seller_id',  $stoer_info['seller_id']);
            session('store_id',  $stoer_info['store_id']);
            session('seller_name',  $stoer_info['seller_name']);
            session('is_admin',  $stoer_info['is_admin']);
            session('seller_group_id',  $stoer_info['seller_group_id']);
            session('seller_quicklink',  $stoer_info['seller_quicklink']);
        }
        session('user_auth', $auth);
        session('user_auth_sign', $this->dataAuthSign($auth));
        // 记住登录
        if ($rememberme) {
            $signin_token = $user->member_name.$user->member_id.$user->member_login_time;
            cookie('uid', $user->member_login_time, 24 * 3600 * 7);
            cookie('signin_token', $this->dataAuthSign($signin_token), 24 * 3600 * 7);
        }
    }

    /**
     * 数据签名认证
     * @param array $data 被认证的数据
     * @author Sunday <153788231@qq.com>
     * @return string 签名
     */
    public function dataAuthSign($data = [])
    {
        // 数据类型检测
        if(!is_array($data)){
            $data = (array)$data;
        }

        // 排序
        ksort($data);
        // url编码并生成query字符串
        $code = http_build_query($data);
        // 生成签名
        $sign = sha1($code);
        return $sign;
    }
    /**
     * 判断是否登录
     * @author Sunday <153788231@qq.com>
     * @return int 0或用户id
     */
    public function isLogin()
    {
        $user = session('user_auth');
        if (empty($user)) {
            // 判断是否记住登录
            if (cookie('?uid') && cookie('?signin_token')) {
                $user = $this::get(cookie('uid'));
                if ($user) {
                    $signin_token = $this->dataAuthSign($user->member_name.$user->member_id.$user->member_login_time);
                    if (cookie('signin_token') == $signin_token) {
                        // 自动登录
                        $this->autoLogin($user, true);
                        return $user->id;
                    }
                }
            };
            return 0;
        }else{
            return session('user_auth_sign') == $this->dataAuthSign($user) ? $user['uid'] : 0;
        }
    }
}
